package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.system.service.ISysDeptTreeService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysDeptTreeServiceImpl implements ISysDeptTreeService {

    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> deptList = new ArrayList<>();
        List<Long> deptIdList = new ArrayList<>();
        for (SysDept SysDept : depts) {
            deptIdList.add(SysDept.getDeptId());
        }
        for (SysDept SysDept : depts) {
            // 如果是顶级节点，遍历该父节点所有子节点
            if (!deptIdList.contains(SysDept.getParentId())) {
                recursionFn(depts, SysDept);
                deptList.add(SysDept);
            }
        }
        if (deptList.isEmpty()) {
            deptList = depts;
        }
        return deptList;
    }

    private void recursionFn(List<SysDept> list, SysDept SysDept) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, SysDept);
        SysDept.setChildren(childList);
        for (SysDept tChild : childList) {
            // 如果子节点有下一级节点，得到下一级的节点列表
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    private List<SysDept> getChildList(List<SysDept> list, SysDept SysDept) {
        List<SysDept> deptList = new ArrayList<>();
        for (SysDept d : list) {
            // 遍历非顶级节点，并获得传入参数顶级节点的下一级子节点列表
            if (d.getParentId() != null && d.getParentId().equals(SysDept.getDeptId())) {
                deptList.add(d);
            }
        }
        return deptList;
    }

    /**
     * 判断是否有子节点
     *
     * @param list    节点列表
     * @param SysDept 部门节点
     * @return Boolean
     */
    private boolean hasChild(List<SysDept> list, SysDept SysDept) {
        return getChildList(list, SysDept).size() > 0;
    }
}
